import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: const Text("Roll Widget Demo"),
      ),
      body: InfiniteListViewWidget(),
    ),
  ));
}

class InfiniteListViewWidget extends StatefulWidget {
  @override
  _InfiniteListViewWidgetState createState() => _InfiniteListViewWidgetState();
}

class _InfiniteListViewWidgetState extends State<InfiniteListViewWidget> {
  static const loadingTag = "##loading##";
  var _words = <String>[loadingTag];

  @override
  void initState() {
    super.initState();
    _retrieveData();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const ListTile(
          title: Text("商品列表"),
        ),
        SizedBox(
          //Column中ListView报错无法没有指定高度，需要加SizedBox处理
          // height: 400,
          //Material设计规范中状态栏、导航栏、ListTile高度分别为24、56、56
          height: MediaQuery.of(context).size.height-24-56-56,
          child: ListView.separated(
            itemCount: _words.length,
            itemBuilder: (context, index) {
              //  如果到了表尾
              if (_words[index] == loadingTag) {
                // 不足100条，继续获取数据
                if (_words.length - 1 < 100) {
                  _retrieveData();
                  //  加载时显示loading;
                  return Container(
                    padding: const EdgeInsets.all(16.0),
                    alignment: Alignment.center,
                    child: const SizedBox(
                      width: 24.0,
                      height: 24.0,
                      child: CircularProgressIndicator(
                        strokeWidth: 2.0,
                      ),
                    ),
                  );
                } else {
                  //  已经加载了100条数据，不在获取数据
                  return Container(
                    alignment: Alignment.center,
                    padding: const EdgeInsets.all(16.0),
                    child: const Text(
                      "没有更多了",
                      style: TextStyle(color: Colors.grey),
                    ),
                  );
                }
              }
              //  显示单次列表
              return ListTile(
                title: Text(_words[index]),
              );
            },
            separatorBuilder: (context, index) => const Divider(
              height: .5,
            ),
          ),
        ),
      ],
    );
  }

  void _retrieveData() {
    Future.delayed(const Duration(seconds: 2)).then((e) {
      setState(() {
        _words.insertAll(
          _words.length - 1,
          generateWordPairs().take(20).map((e) => e.asPascalCase).toList(),
        );
      });
    });
  }
}
